import { createRouter, createWebHistory } from "vue-router";
import HomeView from "../views/Home.vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  scrollBehavior() {
    return {
      left: 0,
      top: 0,
    };
  },
  routes: [
    {
      path: "/",
      name: "home",
      component: HomeView,
    },
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/Login.vue"),
    },
    {
      path: "/register",
      name: "register",
      component: () => import("@/views/Register.vue"),
    },
    {
      path: "/categories/:category",
      name: "cat_products",
      props: true,
      component: () => import("@/views/Results.vue"),
    },
    {
      path: "/products",
      name: "products",
      props: (route) => ({ keywords: route.query.keywords }),
      component: () => import("@/views/Results.vue"),
    },
    {
      path: "/products/:id",
      name: "product",
      props: true,
      component: () => import("@/views/Detail.vue"),
    },
    {
      path: "/cart",
      name: "cart",
      meta: {
        notPublic: true,
      },
      component: () => import("@/views/Cart.vue"),
    },
    {
      path: "/userinfo",
      name: "userinfo",
      meta: {
        notPublic: true,
      },
      component: () => import("@/views/UserInfo.vue"),
    },
  ],
});

router.beforeEach((to) => {
  if (to.meta.notPublic && !localStorage.getItem("token")) {
    return "/login";
  }
});

export default router;
